from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGroupBox,
                             QFormLayout, QLineEdit, QSpinBox, QCheckBox,
                             QComboBox, QPushButton, QTextEdit, QLabel,
                             QFileDialog, QMessageBox, QTabWidget, QSlider,
                             QColorDialog, QFontDialog)
from PyQt6.QtCore import Qt, pyqtSignal
from PyQt6.QtGui import QFont, QColor
from typing import Dict, Any
from loguru import logger
import json
from pathlib import Path

from config.settings import get_settings


class SettingsWidget(QWidget):
    """设置组件"""
    
    # 信号定义
    settings_changed = pyqtSignal(dict)  # 设置改变信号
    
    def __init__(self):
        super().__init__()
        self.settings = get_settings()
        self.current_settings = {}
        
        self.init_ui()
        self.load_settings()
        self.setup_connections()
    
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        
        # 创建标签页
        self.tab_widget = QTabWidget()
        
        # 通用设置标签页
        self.tab_widget.addTab(self.create_general_tab(), "通用设置")
        
        # Playwright设置标签页
        self.tab_widget.addTab(self.create_playwright_tab(), "Playwright设置")
        
        # 界面设置标签页
        self.tab_widget.addTab(self.create_ui_tab(), "界面设置")
        
        # 录制设置标签页
        self.tab_widget.addTab(self.create_recording_tab(), "录制设置")
        
        # 执行设置标签页
        self.tab_widget.addTab(self.create_execution_tab(), "执行设置")
        
        # 日志设置标签页
        self.tab_widget.addTab(self.create_logging_tab(), "日志设置")
        
        layout.addWidget(self.tab_widget)
        
        # 操作按钮
        buttons_layout = QHBoxLayout()
        
        self.save_btn = QPushButton("保存设置")
        self.reset_btn = QPushButton("重置默认")
        self.import_btn = QPushButton("导入设置")
        self.export_btn = QPushButton("导出设置")
        
        buttons_layout.addWidget(self.save_btn)
        buttons_layout.addWidget(self.reset_btn)
        buttons_layout.addWidget(self.import_btn)
        buttons_layout.addWidget(self.export_btn)
        buttons_layout.addStretch()
        
        layout.addLayout(buttons_layout)
    
    def create_general_tab(self) -> QWidget:
        """创建通用设置标签页"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 应用信息
        app_group = QGroupBox("应用信息")
        app_layout = QFormLayout(app_group)
        
        self.app_name_input = QLineEdit()
        app_layout.addRow("应用名称:", self.app_name_input)
        
        self.app_version_label = QLabel()
        app_layout.addRow("应用版本:", self.app_version_label)
        
        layout.addWidget(app_group)
        
        # 文件路径设置
        paths_group = QGroupBox("路径设置")
        paths_layout = QFormLayout(paths_group)
        
        # 脚本目录
        scripts_dir_layout = QHBoxLayout()
        self.scripts_dir_input = QLineEdit()
        scripts_dir_browse_btn = QPushButton("浏览")
        scripts_dir_browse_btn.clicked.connect(self.browse_scripts_dir)
        scripts_dir_layout.addWidget(self.scripts_dir_input)
        scripts_dir_layout.addWidget(scripts_dir_browse_btn)
        paths_layout.addRow("脚本目录:", scripts_dir_layout)
        
        # 最大脚本数量
        self.max_scripts_spinbox = QSpinBox()
        self.max_scripts_spinbox.setRange(10, 10000)
        paths_layout.addRow("最大脚本数量:", self.max_scripts_spinbox)
        
        layout.addWidget(paths_group)
        
        # 性能设置
        performance_group = QGroupBox("性能设置")
        performance_layout = QFormLayout(performance_group)
        
        # 自动保存
        self.auto_save_checkbox = QCheckBox("启用自动保存")
        performance_layout.addRow("自动保存:", self.auto_save_checkbox)
        
        self.auto_save_interval_spinbox = QSpinBox()
        self.auto_save_interval_spinbox.setRange(30, 600)
        self.auto_save_interval_spinbox.setSuffix(" 秒")
        performance_layout.addRow("自动保存间隔:", self.auto_save_interval_spinbox)
        
        # 内存限制
        self.memory_limit_spinbox = QSpinBox()
        self.memory_limit_spinbox.setRange(512, 8192)
        self.memory_limit_spinbox.setSuffix(" MB")
        performance_layout.addRow("内存限制:", self.memory_limit_spinbox)
        
        layout.addWidget(performance_group)
        
        layout.addStretch()
        return widget
    
    def create_playwright_tab(self) -> QWidget:
        """创建Playwright设置标签页"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 浏览器设置
        browser_group = QGroupBox("浏览器设置")
        browser_layout = QFormLayout(browser_group)
        
        # 默认浏览器
        self.browser_type_combo = QComboBox()
        self.browser_type_combo.addItems(["chromium", "firefox", "webkit"])
        browser_layout.addRow("默认浏览器:", self.browser_type_combo)
        
        # 无头模式
        self.headless_checkbox = QCheckBox("默认无头模式")
        browser_layout.addRow("显示模式:", self.headless_checkbox)
        
        # 超时设置
        self.timeout_spinbox = QSpinBox()
        self.timeout_spinbox.setRange(5000, 120000)
        self.timeout_spinbox.setSuffix(" ms")
        browser_layout.addRow("默认超时:", self.timeout_spinbox)
        
        # 用户代理
        self.user_agent_input = QLineEdit()
        self.user_agent_input.setPlaceholderText("留空使用默认用户代理")
        browser_layout.addRow("用户代理:", self.user_agent_input)
        
        layout.addWidget(browser_group)
        
        # 页面设置
        page_group = QGroupBox("页面设置")
        page_layout = QFormLayout(page_group)
        
        # 视窗大小
        viewport_layout = QHBoxLayout()
        self.viewport_width_spinbox = QSpinBox()
        self.viewport_width_spinbox.setRange(800, 2560)
        self.viewport_height_spinbox = QSpinBox()
        self.viewport_height_spinbox.setRange(600, 1440)
        viewport_layout.addWidget(self.viewport_width_spinbox)
        viewport_layout.addWidget(QLabel("x"))
        viewport_layout.addWidget(self.viewport_height_spinbox)
        viewport_layout.addStretch()
        page_layout.addRow("视窗大小:", viewport_layout)
        
        # 设备仿真
        self.device_emulation_checkbox = QCheckBox("启用设备仿真")
        page_layout.addRow("设备仿真:", self.device_emulation_checkbox)
        
        self.device_type_combo = QComboBox()
        self.device_type_combo.addItems([
            "Desktop", "iPhone 12", "iPad", "Android Phone", "Android Tablet"
        ])
        page_layout.addRow("设备类型:", self.device_type_combo)
        
        layout.addWidget(page_group)
        
        # 网络设置
        network_group = QGroupBox("网络设置")
        network_layout = QFormLayout(network_group)
        
        # 代理设置
        self.proxy_enabled_checkbox = QCheckBox("启用代理")
        network_layout.addRow("代理:", self.proxy_enabled_checkbox)
        
        self.proxy_server_input = QLineEdit()
        self.proxy_server_input.setPlaceholderText("http://proxy.example.com:8080")
        network_layout.addRow("代理服务器:", self.proxy_server_input)
        
        # 网络限制
        self.network_throttling_checkbox = QCheckBox("启用网络限制")
        network_layout.addRow("网络限制:", self.network_throttling_checkbox)
        
        self.network_speed_combo = QComboBox()
        self.network_speed_combo.addItems(["Fast 3G", "Slow 3G", "2G", "无限制"])
        network_layout.addRow("网络速度:", self.network_speed_combo)
        
        layout.addWidget(network_group)
        
        layout.addStretch()
        return widget
    
    def create_ui_tab(self) -> QWidget:
        """创建界面设置标签页"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 外观设置
        appearance_group = QGroupBox("外观设置")
        appearance_layout = QFormLayout(appearance_group)
        
        # 主题
        self.theme_combo = QComboBox()
        self.theme_combo.addItems(["light", "dark", "auto"])
        appearance_layout.addRow("主题:", self.theme_combo)
        
        # 窗口大小
        window_size_layout = QHBoxLayout()
        self.window_width_spinbox = QSpinBox()
        self.window_width_spinbox.setRange(800, 2560)
        self.window_height_spinbox = QSpinBox()
        self.window_height_spinbox.setRange(600, 1440)
        window_size_layout.addWidget(self.window_width_spinbox)
        window_size_layout.addWidget(QLabel("x"))
        window_size_layout.addWidget(self.window_height_spinbox)
        window_size_layout.addStretch()
        appearance_layout.addRow("默认窗口大小:", window_size_layout)
        
        # 字体设置
        font_layout = QHBoxLayout()
        self.font_label = QLabel("默认字体")
        font_choose_btn = QPushButton("选择字体")
        font_choose_btn.clicked.connect(self.choose_font)
        font_layout.addWidget(self.font_label)
        font_layout.addWidget(font_choose_btn)
        font_layout.addStretch()
        appearance_layout.addRow("界面字体:", font_layout)
        
        # 代码字体
        code_font_layout = QHBoxLayout()
        self.code_font_label = QLabel("Consolas, 10pt")
        code_font_choose_btn = QPushButton("选择字体")
        code_font_choose_btn.clicked.connect(self.choose_code_font)
        code_font_layout.addWidget(self.code_font_label)
        code_font_layout.addWidget(code_font_choose_btn)
        code_font_layout.addStretch()
        appearance_layout.addRow("代码字体:", code_font_layout)
        
        layout.addWidget(appearance_group)
        
        # 编辑器设置
        editor_group = QGroupBox("编辑器设置")
        editor_layout = QFormLayout(editor_group)
        
        # 语法高亮
        self.syntax_highlight_checkbox = QCheckBox("启用语法高亮")
        editor_layout.addRow("语法高亮:", self.syntax_highlight_checkbox)
        
        # 行号显示
        self.line_numbers_checkbox = QCheckBox("显示行号")
        editor_layout.addRow("行号:", self.line_numbers_checkbox)
        
        # 自动缩进
        self.auto_indent_checkbox = QCheckBox("自动缩进")
        editor_layout.addRow("自动缩进:", self.auto_indent_checkbox)
        
        # Tab大小
        self.tab_size_spinbox = QSpinBox()
        self.tab_size_spinbox.setRange(2, 8)
        editor_layout.addRow("Tab大小:", self.tab_size_spinbox)
        
        layout.addWidget(editor_group)
        
        layout.addStretch()
        return widget
    
    def create_recording_tab(self) -> QWidget:
        """创建录制设置标签页"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 录制选项
        recording_group = QGroupBox("录制选项")
        recording_layout = QFormLayout(recording_group)
        
        # 自动等待
        self.recording_auto_wait_checkbox = QCheckBox("动作间自动等待")
        recording_layout.addRow("自动等待:", self.recording_auto_wait_checkbox)
        
        self.recording_wait_time_spinbox = QSpinBox()
        self.recording_wait_time_spinbox.setRange(100, 5000)
        self.recording_wait_time_spinbox.setSuffix(" ms")
        recording_layout.addRow("等待时间:", self.recording_wait_time_spinbox)
        
        # 智能选择器
        self.smart_selector_checkbox = QCheckBox("智能选择器生成")
        recording_layout.addRow("智能选择器:", self.smart_selector_checkbox)
        
        # 录制过滤
        self.record_mouse_move_checkbox = QCheckBox("录制鼠标移动")
        recording_layout.addRow("鼠标移动:", self.record_mouse_move_checkbox)
        
        self.record_scroll_checkbox = QCheckBox("录制滚动事件")
        recording_layout.addRow("滚动事件:", self.record_scroll_checkbox)
        
        layout.addWidget(recording_group)
        
        # 代码生成设置
        codegen_group = QGroupBox("代码生成设置")
        codegen_layout = QFormLayout(codegen_group)
        
        # 代码风格
        self.code_style_combo = QComboBox()
        self.code_style_combo.addItems(["PEP8", "Google", "Facebook"])
        codegen_layout.addRow("代码风格:", self.code_style_combo)
        
        # 注释生成
        self.generate_comments_checkbox = QCheckBox("生成注释")
        codegen_layout.addRow("生成注释:", self.generate_comments_checkbox)
        
        # 断言建议
        self.suggest_assertions_checkbox = QCheckBox("自动建议断言")
        codegen_layout.addRow("断言建议:", self.suggest_assertions_checkbox)
        
        layout.addWidget(codegen_group)
        
        layout.addStretch()
        return widget
    
    def create_execution_tab(self) -> QWidget:
        """创建执行设置标签页"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 执行选项
        execution_group = QGroupBox("执行选项")
        execution_layout = QFormLayout(execution_group)
        
        # 默认超时
        self.execution_timeout_spinbox = QSpinBox()
        self.execution_timeout_spinbox.setRange(10, 600)
        self.execution_timeout_spinbox.setSuffix(" 秒")
        execution_layout.addRow("默认超时:", self.execution_timeout_spinbox)
        
        # 重试设置
        self.execution_retry_checkbox = QCheckBox("启用失败重试")
        execution_layout.addRow("失败重试:", self.execution_retry_checkbox)
        
        self.execution_retry_count_spinbox = QSpinBox()
        self.execution_retry_count_spinbox.setRange(1, 5)
        execution_layout.addRow("重试次数:", self.execution_retry_count_spinbox)
        
        # 并发执行
        self.parallel_execution_checkbox = QCheckBox("支持并发执行")
        execution_layout.addRow("并发执行:", self.parallel_execution_checkbox)
        
        self.max_parallel_spinbox = QSpinBox()
        self.max_parallel_spinbox.setRange(1, 10)
        execution_layout.addRow("最大并发数:", self.max_parallel_spinbox)
        
        layout.addWidget(execution_group)
        
        # 结果设置
        results_group = QGroupBox("结果设置")
        results_layout = QFormLayout(results_group)
        
        # 保存输出
        self.save_output_checkbox = QCheckBox("保存执行输出")
        results_layout.addRow("保存输出:", self.save_output_checkbox)
        
        # 截图设置
        self.take_screenshots_checkbox = QCheckBox("失败时自动截图")
        results_layout.addRow("自动截图:", self.take_screenshots_checkbox)
        
        # 历史记录限制
        self.history_limit_spinbox = QSpinBox()
        self.history_limit_spinbox.setRange(10, 1000)
        results_layout.addRow("历史记录限制:", self.history_limit_spinbox)
        
        layout.addWidget(results_group)
        
        layout.addStretch()
        return widget
    
    def create_logging_tab(self) -> QWidget:
        """创建日志设置标签页"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 日志级别
        level_group = QGroupBox("日志级别")
        level_layout = QFormLayout(level_group)
        
        self.log_level_combo = QComboBox()
        self.log_level_combo.addItems(["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"])
        level_layout.addRow("日志级别:", self.log_level_combo)
        
        # 控制台日志
        self.console_log_checkbox = QCheckBox("显示控制台日志")
        level_layout.addRow("控制台输出:", self.console_log_checkbox)
        
        layout.addWidget(level_group)
        
        # 文件日志
        file_group = QGroupBox("文件日志")
        file_layout = QFormLayout(file_group)
        
        # 日志文件路径
        log_file_layout = QHBoxLayout()
        self.log_file_input = QLineEdit()
        log_file_browse_btn = QPushButton("浏览")
        log_file_browse_btn.clicked.connect(self.browse_log_file)
        log_file_layout.addWidget(self.log_file_input)
        log_file_layout.addWidget(log_file_browse_btn)
        file_layout.addRow("日志文件:", log_file_layout)
        
        # 文件大小限制
        self.log_file_size_spinbox = QSpinBox()
        self.log_file_size_spinbox.setRange(1, 100)
        self.log_file_size_spinbox.setSuffix(" MB")
        file_layout.addRow("文件大小限制:", self.log_file_size_spinbox)
        
        # 保留天数
        self.log_retention_days_spinbox = QSpinBox()
        self.log_retention_days_spinbox.setRange(1, 365)
        self.log_retention_days_spinbox.setSuffix(" 天")
        file_layout.addRow("保留天数:", self.log_retention_days_spinbox)
        
        layout.addWidget(file_group)
        
        layout.addStretch()
        return widget
    
    def setup_connections(self):
        """设置信号连接"""
        # 操作按钮
        self.save_btn.clicked.connect(self.save_settings)
        self.reset_btn.clicked.connect(self.reset_settings)
        self.import_btn.clicked.connect(self.import_settings)
        self.export_btn.clicked.connect(self.export_settings)
        
        # 设置项改变时的连接（可以添加实时验证等）
        pass
    
    def load_settings(self):
        """加载设置"""
        try:
            # 通用设置
            self.app_name_input.setText(self.settings.app_name)
            self.app_version_label.setText(self.settings.app_version)
            self.scripts_dir_input.setText(self.settings.scripts_dir)
            self.max_scripts_spinbox.setValue(self.settings.max_scripts)
            
            # Playwright设置
            self.browser_type_combo.setCurrentText(self.settings.browser_type)
            self.headless_checkbox.setChecked(self.settings.headless)
            self.timeout_spinbox.setValue(self.settings.timeout)
            
            # 界面设置
            self.theme_combo.setCurrentText(self.settings.theme)
            self.window_width_spinbox.setValue(self.settings.window_width)
            self.window_height_spinbox.setValue(self.settings.window_height)
            
            # 日志设置
            self.log_level_combo.setCurrentText(self.settings.log_level)
            self.log_file_input.setText(self.settings.log_file)
            
            # 设置默认值（对于配置文件中没有的新选项）
            self.auto_save_checkbox.setChecked(True)
            self.auto_save_interval_spinbox.setValue(60)
            self.memory_limit_spinbox.setValue(1024)
            self.viewport_width_spinbox.setValue(1280)
            self.viewport_height_spinbox.setValue(720)
            self.syntax_highlight_checkbox.setChecked(True)
            self.line_numbers_checkbox.setChecked(True)
            self.auto_indent_checkbox.setChecked(True)
            self.tab_size_spinbox.setValue(4)
            self.recording_auto_wait_checkbox.setChecked(True)
            self.recording_wait_time_spinbox.setValue(500)
            self.smart_selector_checkbox.setChecked(True)
            self.generate_comments_checkbox.setChecked(True)
            self.execution_timeout_spinbox.setValue(60)
            self.execution_retry_checkbox.setChecked(False)
            self.execution_retry_count_spinbox.setValue(1)
            self.history_limit_spinbox.setValue(100)
            self.log_file_size_spinbox.setValue(10)
            self.log_retention_days_spinbox.setValue(30)
            
            logger.info("已加载设置")
            
        except Exception as e:
            logger.error(f"加载设置失败: {e}")
            QMessageBox.warning(self, "警告", f"加载设置失败: {str(e)}")
    
    def save_settings(self):
        """保存设置"""
        try:
            # 收集所有设置
            new_settings = {
                # 通用设置
                "app_name": self.app_name_input.text(),
                "scripts_dir": self.scripts_dir_input.text(),
                "max_scripts": self.max_scripts_spinbox.value(),
                
                # Playwright设置
                "browser_type": self.browser_type_combo.currentText(),
                "headless": self.headless_checkbox.isChecked(),
                "timeout": self.timeout_spinbox.value(),
                
                # 界面设置
                "theme": self.theme_combo.currentText(),
                "window_width": self.window_width_spinbox.value(),
                "window_height": self.window_height_spinbox.value(),
                
                # 日志设置
                "log_level": self.log_level_combo.currentText(),
                "log_file": self.log_file_input.text(),
                
                # 扩展设置
                "auto_save": self.auto_save_checkbox.isChecked(),
                "auto_save_interval": self.auto_save_interval_spinbox.value(),
                "viewport_width": self.viewport_width_spinbox.value(),
                "viewport_height": self.viewport_height_spinbox.value(),
                "syntax_highlight": self.syntax_highlight_checkbox.isChecked(),
                "recording_auto_wait": self.recording_auto_wait_checkbox.isChecked(),
                "recording_wait_time": self.recording_wait_time_spinbox.value(),
                "execution_timeout": self.execution_timeout_spinbox.value(),
                "execution_retry": self.execution_retry_checkbox.isChecked(),
                "history_limit": self.history_limit_spinbox.value()
            }
            
            # 验证设置
            validation_result = self.validate_settings(new_settings)
            if not validation_result["valid"]:
                QMessageBox.warning(self, "设置错误", validation_result["error"])
                return
            
            # 保存到配置文件
            self.save_settings_to_file(new_settings)
            
            # 发射设置改变信号
            self.settings_changed.emit(new_settings)
            
            QMessageBox.information(self, "成功", "设置已保存，部分设置需要重启应用后生效")
            logger.info("设置已保存")
            
        except Exception as e:
            logger.error(f"保存设置失败: {e}")
            QMessageBox.critical(self, "错误", f"保存设置失败: {str(e)}")
    
    def validate_settings(self, settings: Dict[str, Any]) -> Dict[str, Any]:
        """验证设置"""
        try:
            # 验证脚本目录
            scripts_dir = Path(settings["scripts_dir"])
            if not scripts_dir.exists():
                try:
                    scripts_dir.mkdir(parents=True, exist_ok=True)
                except:
                    return {"valid": False, "error": f"无法创建脚本目录: {scripts_dir}"}
            
            # 验证日志文件目录
            log_file = Path(settings["log_file"])
            log_dir = log_file.parent
            if not log_dir.exists():
                try:
                    log_dir.mkdir(parents=True, exist_ok=True)
                except:
                    return {"valid": False, "error": f"无法创建日志目录: {log_dir}"}
            
            # 验证数值范围
            if settings["timeout"] < 1000:
                return {"valid": False, "error": "超时时间不能小于1000毫秒"}
            
            if settings["window_width"] < 800 or settings["window_height"] < 600:
                return {"valid": False, "error": "窗口大小不能小于800x600"}
            
            return {"valid": True, "error": None}
            
        except Exception as e:
            return {"valid": False, "error": str(e)}
    
    def save_settings_to_file(self, settings: Dict[str, Any]):
        """保存设置到文件"""
        try:
            settings_file = Path("config/user_settings.json")
            settings_file.parent.mkdir(exist_ok=True)
            
            with open(settings_file, 'w', encoding='utf-8') as f:
                json.dump(settings, f, ensure_ascii=False, indent=2)
                
        except Exception as e:
            logger.error(f"保存设置文件失败: {e}")
            raise
    
    def reset_settings(self):
        """重置为默认设置"""
        reply = QMessageBox.question(
            self, "确认重置", "确定要重置所有设置为默认值吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            # 重新加载默认设置
            self.settings = get_settings()
            self.load_settings()
            QMessageBox.information(self, "成功", "设置已重置为默认值")
    
    def import_settings(self):
        """导入设置"""
        try:
            file_path, _ = QFileDialog.getOpenFileName(
                self, "导入设置", "", "JSON文件 (*.json)"
            )
            
            if file_path:
                with open(file_path, 'r', encoding='utf-8') as f:
                    imported_settings = json.load(f)
                
                # 应用导入的设置
                self.apply_imported_settings(imported_settings)
                
                QMessageBox.information(self, "成功", "设置已导入")
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导入设置失败: {str(e)}")
    
    def export_settings(self):
        """导出设置"""
        try:
            file_path, _ = QFileDialog.getSaveFileName(
                self, "导出设置", "ui_autotools_settings.json", "JSON文件 (*.json)"
            )
            
            if file_path:
                current_settings = self.collect_current_settings()
                
                with open(file_path, 'w', encoding='utf-8') as f:
                    json.dump(current_settings, f, ensure_ascii=False, indent=2)
                
                QMessageBox.information(self, "成功", f"设置已导出到: {file_path}")
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导出设置失败: {str(e)}")
    
    def apply_imported_settings(self, settings: Dict[str, Any]):
        """应用导入的设置"""
        # 安全地应用设置，忽略无效的设置项
        try:
            if "app_name" in settings:
                self.app_name_input.setText(settings["app_name"])
            if "browser_type" in settings:
                self.browser_type_combo.setCurrentText(settings["browser_type"])
            if "theme" in settings:
                self.theme_combo.setCurrentText(settings["theme"])
            # 添加更多设置项的导入逻辑...
            
        except Exception as e:
            logger.warning(f"应用部分导入设置失败: {e}")
    
    def collect_current_settings(self) -> Dict[str, Any]:
        """收集当前设置"""
        return {
            "app_name": self.app_name_input.text(),
            "browser_type": self.browser_type_combo.currentText(),
            "theme": self.theme_combo.currentText(),
            "window_width": self.window_width_spinbox.value(),
            "window_height": self.window_height_spinbox.value(),
            # 添加更多设置项...
        }
    
    def browse_scripts_dir(self):
        """浏览脚本目录"""
        dir_path = QFileDialog.getExistingDirectory(self, "选择脚本目录")
        if dir_path:
            self.scripts_dir_input.setText(dir_path)
    
    def browse_log_file(self):
        """浏览日志文件"""
        file_path, _ = QFileDialog.getSaveFileName(
            self, "选择日志文件", "", "日志文件 (*.log);;所有文件 (*)"
        )
        if file_path:
            self.log_file_input.setText(file_path)
    
    def choose_font(self):
        """选择界面字体"""
        font, ok = QFontDialog.getFont()
        if ok:
            self.font_label.setText(f"{font.family()}, {font.pointSize()}pt")
    
    def choose_code_font(self):
        """选择代码字体"""
        font, ok = QFontDialog.getFont(QFont("Consolas", 10))
        if ok:
            self.code_font_label.setText(f"{font.family()}, {font.pointSize()}pt")